import { defineStore } from 'pinia'
import axios from '../utils/axios'

export const useUserStore = defineStore('user', {
    state: () => ({
        username: localStorage.getItem('username') || '',
        token: localStorage.getItem('token') || ''
    }),
    actions: {
        async login(userData) {
            try {
                const response = await axios.post('/user/login', userData)
                if (response.code === 200) {
                    const { username, token } = response.data
                    this.username = username
                    this.token = token
                    localStorage.setItem('username', username)
                    localStorage.setItem('token', token)
                    return { success: true }
                } else {
                    return { success: false, message: response.message }
                }
            } catch (error) {
                console.error('登录失败:', error)
                const errorMsg = error.response?.data?.message || '用户不存在，请先注册'
                return { success: false, message: errorMsg }
            }
        },
        // 用户注册
        async register(userData) {
            try {
                await axios.post('/user/register', userData)
                return { success: true }
            } catch (error) {
                console.error('注册失败:', error)
                return { success: false, message: error.response.data.message }
            }
        },
        // 退出登录
        logout() {
            this.username = ''
            this.token = ''
            localStorage.removeItem('username')
            localStorage.removeItem('token')
        }
    }
})
